package com.ctvit.sjk.knowledge.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ctvit.sjk.knowledge.app.pojo.domain.TabApp;
import com.ctvit.sjk.knowledge.app.pojo.dto.AppCreateDTO;
import com.ctvit.sjk.knowledge.app.pojo.dto.AppUpdateDTO;
import com.ctvit.sjk.knowledge.app.pojo.vo.AppAuthenticationVO;
import com.ctvit.sjk.knowledge.app.pojo.vo.AppGetVO;
import com.ctvit.sjk.knowledge.app.service.ITabAppService;
import com.ctvit.sjk.knowledge.core.controller.KnowledgeController;
import com.ctvit.sjk.knowledge.core.enums.QueryTypeEnum;
import com.ctvit.sjk.knowledge.core.page.TableRecordInfo;
import com.ctvit.sjk.knowledge.dataset.pojo.domain.TabDataset;
import com.ctvit.sjk.knowledge.dataset.pojo.vo.DatasetGetVO;
import com.ctvit.sjk.knowledge.dataset.service.ITabDatasetService;
import com.ctvit.sjk.knowledge.model.pojo.domain.TabModel;
import com.ctvit.sjk.knowledge.model.pojo.vo.ModelViewVO;
import com.ctvit.sjk.knowledge.model.service.ITabModelService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 应用Controller
 *
 * @author heyingcheng
 * @date 2025/3/22
 */
@Slf4j
@RestController
@RequestMapping("knowledge/application")
public class TabAppController extends KnowledgeController {

    private final ITabAppService tabAppService;

    private final ITabModelService tabModelService;

    private final ITabDatasetService tabDatasetService;

    public TabAppController(ITabAppService tabAppService, ITabModelService tabModelService, ITabDatasetService tabDatasetService) {
        this.tabAppService = tabAppService;
        this.tabModelService = tabModelService;
        this.tabDatasetService = tabDatasetService;
    }

    /**
     * 查询应用列表
     */
    @GetMapping("{pageNum}/{pageSize}")
    public TableRecordInfo list(@PathVariable int pageNum,
                                @PathVariable int pageSize,
                                @RequestParam(value = "select_user_id", defaultValue = "all") String type,
                                @RequestParam(defaultValue = "") String name) {
        LambdaQueryWrapper<TabApp> wrapper = new LambdaQueryWrapper<>();
        if (QueryTypeEnum.MY.getCode().equals(type)) {
            wrapper.eq(TabApp::getCreateId, CREATE_ID);
        }
        wrapper.like(StringUtils.isNotBlank(name), TabApp::getAppName, name);
        wrapper.orderByDesc(TabApp::getUpdateTime);

        startPage(pageNum, pageSize);
        List<TabApp> list = tabAppService.list(wrapper);
        return getRecordTable(list.stream().map(AppGetVO::new).collect(Collectors.toList()), pageNum, pageSize);
    }

    /**
     * 创建应用
     */
    @Log(title = "应用", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult create(@RequestBody AppCreateDTO dto) {
        return success(tabAppService.create(dto, CREATE_ID));
    }

    /**
     * 修改应用
     */
    @Log(title = "应用", businessType = BusinessType.UPDATE)
    @PutMapping("{appId}")
    public AjaxResult update(@PathVariable String appId, @RequestBody AppUpdateDTO dto) {
        return success(tabAppService.update(appId, dto, CREATE_ID));
    }

    /**
     * 获取应用
     */
    @GetMapping("{appId}")
    public AjaxResult get(@PathVariable String appId) {
        return success(new AppGetVO(tabAppService.getById(appId)));
    }

    /**
     * 获取应用列表
     */
    @GetMapping()
    public AjaxResult list() {
        LambdaQueryWrapper<TabApp> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(TabApp::getAppName);
        return success(tabAppService.list().stream().map(AppGetVO::new).collect(Collectors.toList()));
    }

    /**
     * 获取模型列表
     */
    @GetMapping("{appId}/model")
    public AjaxResult listModel(@PathVariable String appId) {
        LambdaQueryWrapper<TabModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(TabModel::getModelName);
        return success(tabModelService.list(wrapper).stream().map(ModelViewVO::new).collect(Collectors.toList()));
    }

    /**
     * 获取知识库列表
     */
    @GetMapping("{appId}/list_dataset")
    public AjaxResult listDataset(@PathVariable String appId) {
        LambdaQueryWrapper<TabDataset> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(TabDataset::getDatasetName);
        return success(tabDatasetService.list(wrapper).stream().map(DatasetGetVO::new).collect(Collectors.toList()));
    }

    /**
     * 统计聊天记录聚合趋势
     */
    @GetMapping("{appId}/statistics/chat_record_aggregate_trend")
    public AjaxResult statisticsChatRecordAggregateTrend(@PathVariable String appId,
                                                         @RequestParam(value = "start_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
                                                         @RequestParam(value = "end_time", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime) {
        log.info("appId:[{}], startTime:[{}], endTime:[{}]", appId, startTime, endTime);
        return success(Collections.emptyList());
    }

    /**
     * 应用认证
     */
    @GetMapping("profile")
    public AjaxResult profile(HttpServletRequest request) {
        AppAuthenticationVO appAuthenticationVO = parseAppAuthentication(request);
        return success(new AppGetVO(tabAppService.getById(appAuthenticationVO.getApplicationId())));
    }

}
